package dws_topic

import (
	"gorm.io/gorm"
	"server/global"
	"server/model/common/request"
)

type DwsTopicService struct {
}


func (dwsTopicService *DwsTopicService) CreateDwsTopic(dwsTopic *DwsTopic) (err error) {
	err = global.SysDB.Create(dwsTopic).Error
	return err
}


func (dwsTopicService *DwsTopicService) DeleteDwsTopic(dwsTopic DwsTopic) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&DwsTopic{}).Where("id = ?", dwsTopic.ID).Update("deleted_by", dwsTopic.DeletedBy).Error; err != nil {
			return err
		}
		if err = tx.Delete(&dwsTopic).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsTopicService *DwsTopicService) DeleteDwsTopicByIds(ids request.IdsReq, deleted_by uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&DwsTopic{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", ids.Ids).Delete(&DwsTopic{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}


func (dwsTopicService *DwsTopicService) UpdateDwsTopic(dwsTopic DwsTopic) (err error) {
	err = global.SysDB.Save(&dwsTopic).Error
	return err
}


func (dwsTopicService *DwsTopicService) GetDwsTopicById(id uint) (dwsTopic DwsTopic, err error) {
	err = global.SysDB.Where("id = ?", id).First(&dwsTopic).Error
	return
}


func (dwsTopicService *DwsTopicService) GetDwsTopicInfoList(info DwsTopicSearch) (list []DwsTopic, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&DwsTopic{})
	var dwsTopics []DwsTopic
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&dwsTopics).Error
	return dwsTopics, total, err
}


func (dwsTopicService *DwsTopicService) GetAllDwsTopics() (dwsTopic []DwsTopic, err error) {
	err = global.SysDB.Find(&dwsTopic).Error
	return dwsTopic, err
}


func (dwsTopicService *DwsTopicService) GetDwsTopic() (dwsTopic []DwsTopic, err error) {
	err = global.SysDB.Find(&dwsTopic).Error
	return dwsTopic, err
}
